import { RouteLocationNormalized, RouteLocationRaw } from "vue-router";
import { defineStore } from "pinia";
import { isEmpty } from "../../ts/lodash";
import * as lodash from "lodash-es";
import { computed, watch } from "vue";
import { useRouter } from "../router";

export function newDefaultTab(): ITab {
  return { closeable: true, name: "default", label: "默认" };
}

export function newTabFromRoute(route: RouteLocationNormalized): ITab {
  const tab = newDefaultTab();
  tab.name = <string>route.name;
  tab.label = <string>route.name;
  tab.params = route.params;
  tab.closeable = !route.meta.canNotCloseTab;

  return tab;
}

interface ITab {
  name: string; // 唯一标识
  label: string; // 显示的标签
  params?: any; // 需要带的参数
  closeable: boolean; // 是否显示关闭按钮
}

function findITabByName(name: string) {
  return function (value: ITab) {
    return value.name === name;
  };
}

interface store {
  // 当前选中的 Tab
  current: string;
  // 记录当前已有的 TAB
  tabs: ITab[];
}

export const useRouteTabStore = defineStore({
  // 它用于 devtools 并允许恢复状态
  id: "route-tab",
  state: (): store => ({
    current: "",
    tabs: [],
  }),
  actions: {
    findTabByName(name: string): ITab | undefined {
      return this.tabs.find(findITabByName(name));
    },
    findTabIndexByName(name: string): number {
      return this.tabs.findIndex(findITabByName(name));
    },
    addTabByRoute(route: RouteLocationNormalized): RouteLocationNormalized {
      const value = this.findTabByName(<string>route.name);

      if (!value) {
        this.tabs.push(newTabFromRoute(route));
      } else if (!isEmpty(route.params)) {
        value.params = route.params;
      } else if (!isEmpty(value.params)) {
        route.params = value.params;
      }
      return route;
    },
    removeTabByName(name: string) {
      const value = this.findTabIndexByName(name);
      if (value !== -1) {
        this.tabs.splice(value, 1);
      }
      // 删除当前 tab 时换前一个页面
      if (name === this.current) {
        this.current = this.tabs[Math.min(value, this.tabs.length - 1)].name;
      }
    },
  },
});

export function selectOrAddTab(
  to: RouteLocationNormalized
): RouteLocationRaw | boolean {
  console.log(`[router] 切换 Tab 标签处理`);
  const store = useRouteTabStore();

  if (to.meta.useTab) {
    store.current = <string>to.name;
    const route = store.addTabByRoute(to);
    console.log(`[router]`, to.params);
    if (lodash.isEmpty(to.params) && !lodash.isEmpty(route.params)) {
      return route;
    }
  } else {
    store.current = "";
  }

  return true;
}

/**
 * 当前选择的页面 Tab 改变后的处理事件
 */
export function useRouteTabChange() {
  const layoutStore = useRouteTabStore();
  const { route, toName } = useRouter();

  const current = computed<string>(() => {
    return layoutStore.current;
  });

  watch(current, function () {
    if (route.name !== current.value && current.value != "") {
      const tab = layoutStore.findTabByName(current.value);
      console.log(`[currentTabChange] `, tab);
      if (tab) {
        toName(tab.name, tab.params);
      } else {
        toName(current.value);
      }
    }
  });

  const closeHandler = (name: string) => {
    layoutStore.removeTabByName(name);
  };

  return {
    closeHandler,
  };
}
